package com.lynn.cons.data;

import com.lynn.cons.common.net.HttpHelper;
import com.lynn.cons.model.Calend;
import com.lynn.cons.model.ConsFortune;
import ohos.utils.zson.ZSONArray;
import ohos.utils.zson.ZSONObject;

import java.util.ArrayList;
import java.util.function.Consumer;

public class CloudDataService {
    final String HOST = "http://cons.api.lynnce.com:10000";
    final String CALEND_URL = "/api/Calend/GetCalendarByDays?days={day}";
    final String TODAY_CONSFORTUNE_URL = "/api/Cons/getTodayConsFortune?e_Cons={conCode}";
    final String TOMORROW_CONSFORTUNE_URL = "/api/Cons/getTodayConsFortune?e_Cons={conCode}";
    private static CloudDataService instance;

    public static CloudDataService getInstance() {
        if (instance == null) {
            synchronized (CloudDataService.class) {
                if (instance == null) {
                    instance = new CloudDataService();
                }
            }
        }
        return instance;
    }

    /**
     * 远程获取日历，并存入本地数据库
     *
     * @param days     获取几天的日历
     * @param consumer
     */
    public void getCalendarByDays(int days, Consumer<ArrayList<Calend>> consumer) {
        String url = HOST + CALEND_URL.replace("{day}", String.valueOf(days));
        ConsDataService service = ConsDataService.getInstance();
        HttpHelper.getList(url, null, res -> {
            String json = ZSONObject.toZSONString(res);
            ArrayList<Calend> calends = (ArrayList<Calend>) ZSONArray.stringToClassList(json, Calend.class);
            service.insertCalend(calends);
            consumer.accept(calends);
        }, (err) -> {
        });
    }

    /**
     * 远程获取今日/明日运势 并存入本地数据库
     *
     * @param conCode 星座编号
     * @param dayType 今日 = 0  明日 = 1
     */
    public void getConsFortune(int conCode, int dayType, Consumer<ConsFortune> consumer) {
        String url = HOST + (dayType == 0 ? TODAY_CONSFORTUNE_URL : TOMORROW_CONSFORTUNE_URL);
        url = url.replace("{conCode}", String.valueOf(conCode));
        ConsDataService service = ConsDataService.getInstance();
        HttpHelper.get(url, null, res -> {
            String json = ZSONObject.toZSONString(res);
            ConsFortune consFortune = ZSONObject.stringToClass(json, ConsFortune.class);
            service.insertOrUpdateConsFortune(consFortune);
            consumer.accept(consFortune);
        }, (err) -> {
        });
    }
}
